<template>
	<view class="page-wrapper">
		<!-- 状态栏占位 -->
		<view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

		<!-- 顶部导航栏 -->
		<view class="navbar">
			<view class="nav-left" @click="goBack">
				<image src="@/static/img/icon-Get-into@3.png" mode="aspectFit" style="height: 36rpx;width: 21rpx;" />
			</view>
			<view class="nav-title">登录</view>
			<view class="nav-right"></view>
			<!-- <view class="nav-right" @click="goToRegister">注册</view> -->
		</view>

		<view class="login-container" :style="`background-image: url(${this.buildImageUrl('img/login/bg1@2x.png')})`">
			<!-- 登录内容区域 -->
			<view class="login-content">

				<!-- 微信登录按钮 -->
				<WechatPhoneAuth type="button" text="微信登录" @success="onWechatLoginSuccess"
					@error="onWechatLoginError" @register="onWechatRegister" @bindPhone="onWechatBindPhone"
					@h5Login="weixinLogin" />

				<!-- 其他方式登录 -->
				<view class="login-qt" @click="showPhoneLogin">
					其他方式登录
				</view>

				<!-- 用户协议 -->
				<view class="login-xy">
					<text class="agreement-text">
						登录即代表您已同意
						<text class="agreement-link" @click="showUserAgreement">《优享优品平台用户注册协议》</text>
					</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import api from '@/api/index.js'
import request from '@/api/request.js'
import config, { buildWechatOAuthUrl } from '@/api/config.js'
import md5 from 'md5'
import { saveLoginInfo } from '@/api/auth.js'
import WechatPhoneAuth from '@/components/WechatPhoneAuth/index.vue'

export default {
	components: {
		WechatPhoneAuth
	},
		data() {
			return {
				userIp: '0.0.0.0',
				latitude: 0,
				longitude: 0,
				backIconSrc: '',
				redirectUrl: '' // 登录成功后的重定向地址
			}
		},
		onLoad(options) {
			// 获取重定向地址
			if (options.redirect) {
				this.redirectUrl = decodeURIComponent(options.redirect)
			}
		wx.login({
			success: async (loginRes) => {
				
				if (loginRes.code) {
					const openidResult = await api.wechatApi.getOpenidForMiniProgram({
					  code: loginRes.code
					})
					
				// this.openid = openidResult.data.openid
				uni.setStorageSync('openid',openidResult.data.openid) 
				console.log('获取到openid:', this.openid);
				// 显示支付方式选择
				} else {
					uni.showToast({
						title: '获取code失败',
						icon: 'none'
					});
				}
			},
			fail: (error) => {
				
				uni.showToast({
					title: '失败',
					icon: 'none'
				});
			}
		});
		
		this.getUserIp();
		this.checkToken();
		this.getLocation();
		// 初始化远程图片地址（使用 SERVER_ADDRESS）
		this.backIconSrc = this.buildImageUrl('img/icon-Get-into@3.png');
	},
	methods: {
		// 组装远程图片地址
		buildImageUrl(path) {
			// 获取配置的服务器地址
			const config = getApp().globalData.config || {}
			const serverAddress = config.SERVER_ADDRESS || 'https://weixin.youpin91.com.cn'
			let base = serverAddress || '';
			if (base && !base.endsWith('/')) base += '/';
			if (path && path.startsWith('/')) path = path.slice(1);
			return base + path;
		},


		// 返回上一页
		goBack() {
			uni.navigateBack({
				delta: 1
			});
		},

		// 获取用户IP地址
		async getUserIp() {
			try {
				const result = await request.request({
					url: 'wap/wx_help/getip',
					datas: {},
					showLog: false
				});
				console.log('获取IP结果:', result);
				if (result.r === 0) {
					this.userIp = result.data;
					console.log('用户IP:', this.userIp);
				}
			} catch (error) {
				console.error('获取IP失败:', error);
			}
		},

		// 检查Token
		async checkToken() {
			try {
				const result = await request.request({
					url: 'wap/wx_help/checkToken',
					datas: {},
					showLog: false
				});
				console.log('检查Token结果:', result);
				// 这里可以处理微信相关的配置信息
			} catch (error) {
				console.error('检查Token失败:', error);
			}
		},

		// 获取地理位置
		getLocation() {
			uni.getLocation({
				type: 'gcj02',
				success: (res) => {
					console.log('获取位置成功:', res);
					this.latitude = res.latitude;
					this.longitude = res.longitude;
				},
				fail: (error) => {
					console.error('获取位置失败:', error);
					// 位置获取失败时使用默认值
					this.latitude = 0;
					this.longitude = 0;
				}
			});
		},

		// 跳转到首页活动页面
		async goToActivity() {
			try {
				// 如果有重定向地址，直接跳转到指定页面
				if (this.redirectUrl) {
					// 检查是否是tabbar页面（需要在 pages.json 的 tabBar.list 中配置的页面）
					const tabbarPages = ['/pages/index/index', '/pages/classification/index', '/pages/o2o/index', '/pages/my/index']
					const isTabbarPage = tabbarPages.some(page => this.redirectUrl.includes(page))
					
					if (isTabbarPage) {
						// tabbar页面使用switchTab
						const pagePath = this.redirectUrl.split('?')[0]
						uni.switchTab({
							url: pagePath
						})
					} else {
						// 普通页面（包括购物车）使用navigateBack或reLaunch
						const pages = getCurrentPages()
						if (pages.length > 1) {
							// 有上一页，返回上一页
							uni.navigateBack()
						} else {
							// 没有上一页，跳转到指定页面
							uni.reLaunch({
								url: this.redirectUrl
							})
						}
					}
					return
				}

				// 没有重定向地址，执行原有逻辑
				const result = await request.request({
					url: 'home/home/activity',
					datas: {},
					showLog: false
				});
				console.log('活动页面数据:', result);

				if (result.r === 0) {
					// 跳转到首页
					uni.reLaunch({
						url: '/pages/index/index'
					});
				} else {
					// 即使活动接口失败，也跳转到首页
					uni.reLaunch({
						url: '/pages/index/index'
					});
				}
			} catch (error) {
				console.error('获取活动数据失败:', error);
				// 即使失败也跳转到首页
				uni.reLaunch({
					url: '/pages/index/index'
				});
			}
		},

		// 微信H5登录
		weixinLogin() {
			// #ifdef H5
			const redirectUri = window.location.origin + '/pages/login/login';
			const weixinUrl = buildWechatOAuthUrl(redirectUri);
			window.location.href = weixinUrl;
			// #endif
			
			// #ifndef H5
			uni.showToast({
				title: '请使用微信内置浏览器',
				icon: 'none'
			});
			// #endif

			// #ifdef APP-PLUS
			// App环境下的微信登录
			uni.showToast({
				title: 'App环境下的微信登录待实现',
				icon: 'none'
			});
			// #endif
		},




		// 显示用户协议
		showUserAgreement() {
			uni.navigateTo({
				url: '/pages/identity/agreement'
			});
		},

		// 其它方式登录显示
		showPhoneLogin() {
			uni.navigateTo({
				url: '/pages/login/login_qt'
			});
		},

		// 跳转到注册页面
		goToRegister() {
			uni.navigateTo({
				url: '/pages/login/register'
			});
		},

		// ====== 新的微信登录事件处理方法 ======
		// 微信登录成功
		onWechatLoginSuccess(userInfo) {
			console.log('微信登录成功:', userInfo)
			// 直接跳转，无需提示
			this.goToActivity()
		},

		// 微信登录失败
		onWechatLoginError(error) {
			console.error('微信登录失败:', error)
			uni.showToast({
				title: error || '登录失败，请重试',
				icon: 'none'
			})
		},

		// 微信登录需要注册 - 自动注册
		async onWechatRegister(registerData) {
			console.log('需要注册，开始自动注册:', registerData)
			
			try {
				uni.showLoading({ title: '注册中...' })
				
				// 自动调用注册接口
				const registerResult = await api.userApi.register({
					mobile: registerData.mobile,
					pwd: '', // 微信注册不需要密码
					invite_code: uni.getStorageSync('invite_code') || '',
					region: 0,
					login_ip: this.userIp,
					salt: '1234',
					type: 4, // 微信注册
					longitude: this.longitude,
					latitude: this.latitude,
					unionid: registerData.unionid,
					openid: registerData.openid,
					nickname: '',
					headimgurl: '',
					sex: 0
				})
				
				uni.hideLoading()
				
				if (registerResult.r === 0) {
					// 注册成功，保存用户信息
					saveLoginInfo(registerResult.data, registerResult.data.token)
					
					this.goToActivity()
				} else {
					uni.showToast({
						title: registerResult.msg || '注册失败',
						icon: 'none'
					})
				}
			} catch (error) {
				uni.hideLoading()
				console.error('自动注册失败:', error)
				uni.showToast({
					title: '注册失败，请重试',
					icon: 'none'
				})
			}
		},

		// 微信登录需要绑定手机号
		onWechatBindPhone(bindData) {
			console.log('需要绑定手机号:', bindData)
			// 跳转到手机号绑定页面
			uni.navigateTo({
				url: `/pages/login/phone_bind?openid=${bindData.openid}&unionid=${bindData.unionid}`
			})
		}
	},
	computed: {
		statusBarHeight() {
			return uni.getSystemInfoSync().statusBarHeight || 0;
		}
	}
}
</script>

<style lang="scss" scoped>
/* 页面整体布局 */
.page-wrapper {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background: #f5f5f5;
}

/* 状态栏和导航栏 */
.status-bar {
	width: 100%;
	background: #ff5033;
}

.navbar {
	height: 88rpx;
	padding: 0 30rpx;
	color: white;
	background: #ff5033;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.nav-left {
	width: 80rpx;
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: flex-start;
}

.nav-title {
	font-size: 36rpx;
	font-weight: 500;
	color: white;
	flex: 1;
	text-align: center;
}

.nav-right {
	font-size: 32rpx;
	color: white;
	width: 80rpx;
	text-align: right;
	font-weight: 500;
}

.login-container {
	width: 100%;
	flex: 1;
	/* 背景图改为内联动态样式 */
	position: relative;
	display: flex;
	flex-direction: column;
	// background-repeat: no-repeat;
	background-position: center;
	background-size: 750rpx;
}

.login-content {
	width: 650rpx;
	height: 230rpx;
	position: fixed;
	bottom: 250rpx;
	left: 60rpx;
}


.wx-btn {
	width: 440rpx;
	height: 80rpx;
	line-height: 80rpx;
	margin: 20rpx auto;
	padding-left: 170rpx;
	/* 按钮背景图改为内联动态样式，颜色在内联中设置 */
	color: #fff;
	font-weight: 700;
	border: 1px solid rgba(255, 255, 255, 0.8);
	border-radius: 10rpx;
	font-size: 32rpx;
	display: block;
	text-align: left;
	background-color: #13d151;
	background-repeat: no-repeat;
	background-position: 110rpx center;
	background-size: 42rpx 34rpx;
}

.login-qt {
	text-align: center;
	color: #676767;
	font-size: 30rpx;
	margin-top: 46rpx;
}

.login-xy {
	margin-top: 102rpx;
	text-align: center;
	color: #9c9c9c;
}

.agreement-text {
	color: #9c9c9c;
	font-size: 26rpx;
}

.agreement-link {
	color: #ff5033;
}

// 手机号登录弹窗
.phone-login-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 1000;

	.modal-content {
		background: #fff;
		border-radius: 20px;
		padding: 30px;
		margin: 20px;
		width: calc(100% - 40px);
		max-width: 400px;

		.modal-header {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 30px;

			.modal-title {
				font-size: 18px;
				font-weight: bold;
				color: #333;
			}

			.modal-close {
				font-size: 24px;
				color: #999;
				padding: 5px;
			}
		}

		.phone-form {
			.input-group {
				margin-bottom: 30px;

				.input-item {
					background: #f8f8f8;
					border-radius: 12px;
					height: 50px;
					display: flex;
					align-items: center;
					padding: 0 15px;
					margin-bottom: 15px;
					border: 1px solid #eee;

					&:focus-within {
						border-color: #07c160;
						background: #fff;
					}

					.input-icon {
						width: 16px;
						height: 16px;
						margin-right: 10px;
						opacity: 0.6;
					}

					.input-field {
						flex: 1;
						height: 100%;
						border: none;
						outline: none;
						font-size: 16px;
						background: transparent;
					}

					.code-btn {
						padding: 6px 12px;
						background: #07c160;
						border-radius: 16px;
						margin-left: 8px;

						&.disabled {
							background: #ccc;
						}

						.code-text {
							color: #fff;
							font-size: 12px;
						}
					}
				}
			}

			.phone-login-btn {
				width: 100%;
				height: 50px;
				background: #07c160;
				border-radius: 12px;
				border: none;
				display: flex;
				align-items: center;
				justify-content: center;

				&[disabled] {
					background: #ccc !important;
					opacity: 0.6;
				}

				.btn-text {
					color: #fff;
					font-size: 16px;
					font-weight: 500;
				}
			}
		}
	}
}

// 底部协议
.agreement-section {
	z-index: 1;
	margin-top: auto;
	padding: 0 30px 30px;

	.agreement-check {
		display: flex;
		align-items: center;
		justify-content: center;
		flex-wrap: wrap;
		text-align: center;

		.agreement-text {
			color: #999;
			font-size: 12px;
			margin-right: 4px;
		}

		.agreement-link {
			color: #07c160;
			font-size: 12px;
			text-decoration: underline;
		}
	}
}
</style>
